package com.jsftoolkit.gen.config.impl;

import java.util.HashMap;
import java.util.Map;

import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathFactory;
import javax.xml.xpath.XPathVariableResolver;

import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;

public class XmlEditor {

	/**
	 * Holds variables for the XPath variable resolver.
	 */
	protected ThreadLocal<Map<String, String>> vars = new ThreadLocal<Map<String, String>>() {
		@Override
		protected Map<String, String> initialValue() {
			return new HashMap<String, String>();
		}
	};

	protected XPathFactory xpathFactory;

	protected DocumentBuilder documentBuilder;

	public XmlEditor() throws ParserConfigurationException {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

		documentBuilder = factory.newDocumentBuilder();

		documentBuilder.setEntityResolver(new EntityResolver() {
			public InputSource resolveEntity(String publicId, String systemId) {
				// grrr, facelets...
				if ("-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN"
						.equals(publicId)) {
					return new InputSource(getClass().getResourceAsStream(
							"/com/jsftoolkit/gen/facelet-taglib_1_0.dtd"));
				}
				return null;
			}
		});

		xpathFactory = XPathFactory.newInstance();
		xpathFactory.setXPathVariableResolver(new XPathVariableResolver() {
			public String resolveVariable(QName variableName) {
				return vars.get().get(variableName.getLocalPart());
			}
		});
	}

}
